package com.ljm.boot.seataorder.controller;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.ljm.boot.seataorder.config.FeignConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ljm.boot.Utils.R;
import com.ljm.boot.seataorder.entity.Order;
import com.ljm.boot.seataorder.feign.OrderDetailsFeignClient;
import com.ljm.boot.seataorder.service.OrderService;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import io.seata.spring.annotation.GlobalTransactional;

/**
 * 订单表(Order)表控制层
 *
 * @author LiRui
 * @since 2025-04-07 16:00:11
 */
@RestController
@RequestMapping("order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;
    
    @Resource
    private OrderDetailsFeignClient orderDetailsFeignClient;

    @PostMapping
    @GlobalTransactional
    public R insert(@RequestBody Order order) {
        try {
            // 打印当前 XID
            log.info("当前事务 XID: {}", io.seata.core.context.RootContext.getXID());
            
            order.setCreateTime(new Date());
            // 保存订单
            boolean saved = this.orderService.save(order);
            if (!saved) {
                throw new RuntimeException("订单保存失败");
            }

            // 使用 Feign 客户端调用
            Map<String, Object> param = new HashMap<>();
            param.put("oId", order.getId());
            param.put("createTime", order.getCreateTime());
            R response = orderDetailsFeignClient.createOrderDetails(param);
//            if(response.getCode().equals(200)){
//                throw new RuntimeException("测试分布式事务回滚");
//            }
            return R.ok();
        } catch (Exception e) {
            log.error("创建订单失败", e);
            throw new RuntimeException("创建订单失败", e);
        }
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Order selectOne(@PathVariable Serializable id) {
        return this.orderService.getById(id);
    }

    /**
     * 修改数据
     *
     * @param order 实体对象
     * @return 修改结果
     */
    @PutMapping
    public void update(@RequestBody Order order) {
         this.orderService.updateById(order);
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public void delete(@RequestParam("idList") List<Long> idList) {
         this.orderService.removeByIds(idList);
    }

    public static void main(String[] args) {
        HttpRequest post = HttpUtil.createPost("http://127.0.0.1:9002/orderDetails");
        Map<String, Object> param = new HashMap<>();
        param.put("oId", 1);
        param.put("createTime", new Date());
        HttpResponse execute = post.body(JSONUtil.toJsonStr(param)).header("Content-Type", "application/json").execute();
        System.out.println(execute.body());
    }
}

